var offset = 0;
var limit = 20;
var pagingLimit = 20;//显示分页时的条数
var currentTotalElements = 0;//当前显示总条数
var pageLoading = true;//是否能滚动加载
var hasShowPages = false;//是否已显示分页
var firstLoadPages = true;//分页初始化时 不自动加载
//筛选条件,
var search_carNumber = null;
var search_employName = null;
var search_companyName = null;
var search_line = null;
var search_status = [];

$(function () {
    //高级搜索
    initdata(false);
    $(".query-jiant").click(function () {
        var src = $("#jiant").attr("src");
        if (src.indexOf("jiant2") >= 0) {
            $("#jiant").attr("src", ctx + "/assets/img/jiant.png");
            $(".choose").show(300);
        } else {
            $("#jiant").attr("src", ctx + "/assets/img/jiant2.png");
            $(".choose").hide(300);
        }
    });
    $("#searchButton").click(function () {
        search_carNumber = $("#carNumber1").val();
        search_employName = $("#employName1").val();
        search_companyName = $("#companyName1").val();
        search_line = $("#line1").val();
        var statusArr = [];
        $("input[name=status]:checked").each(function (index, element) {
            statusArr.push($(element).val());
        });
        if (null != statusArr && statusArr.length > 0) {
            search_status = statusArr.join(",");
        } else {
            search_status = [];
        }
        offset = 0;
        initdata(false);
    });
    $(document).on("keydown", "body", function () {
        if (window.event.keyCode == 13) {
            $("#searchButton").click();
        }
    });
    $(window).scroll(function () {
        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
        //$(window).height()获取当前窗体的高度
        //$(document).height()获取当前文档的高度
        var bot = 0; //bot是底部距离的高度
        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
            //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
            if (pageLoading) {
                pageLoading = false;
                offset += limit;
                initdata(true);
            }
        }
    });

});


function initdata(isappend) {
    $.ajax({
        url: window.daijia.ctx + '/zhuanxian/carsData',
        type: 'GET',
        async: false,
        dataType: 'json',
        data: {
            "carNumber": search_carNumber,
            "employName": search_employName,
            "company": search_companyName,
            "lineName": search_line,
            "status": search_status,
            "pager.offset": offset,
            "limit": limit,
        },
        success: function (result) {
            var authority = result.content[0].authority;
            var newcontent = '';
            var totalElements = result.totalElements;
            if (totalElements > 0) {
                $(result.content[0].cars).each(function (index, data) {
                    // console.log('carId:'+data.id + ',lineId:'+data.lineId);

                    var lines = data.lines;
                    var paramLines = '';
                    if (null != data.lines) {
                        $.each(lines, function (i, it) {
                            paramLines += it.id;
                            if (i < lines.length - 1) {
                                paramLines += ',';
                            }

                        })
                    }
                    var statusColor = "";
                    var mainButton = "";
                    var selectButton = "";
                    statusColor = "btn-primary";
                    if(authority.indexOf("editZXVehicle") > -1){
                        mainButton = "<a href='#' data-value='" + data.id + "' class='btn btn-primary btn-xs updatethis'>编辑</a>";
                    }
                    if(authority.indexOf("deleteZXVehicle") > -1){
                        selectButton += "<button type='button' class='btn " + statusColor + " btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>" +
                            "<span class='caret'></span>" +
                            "<span class='sr-only'>Toggle Dropdown</span>" +
                            "</button>" +
                            "<ul class='dropdown-menu' role='menu'>" +
                            "<li style='cursor:pointer;'><a href='#' data-lineId='" + paramLines + "'  data-value='" + data.id + "'  class='btn-link deletethis'>删除</a></li>"+
                            "</ul>" +
                            "</div>";
                    }
                    var allButton = "<div class='btn-group'>" + mainButton + selectButton;
                        // "<button type='button' class='btn " + statusColor + " btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>" +
                        // "<span class='caret'></span>" +
                        // "<span class='sr-only'>Toggle Dropdown</span>" +
                        // "</button>" +
                        // "<ul class='dropdown-menu' role='menu'>" +
                        // selectButton +
                        // "</ul>" +
                        // "</div>";

                    var status = "";
                    if (data.status == 1) {
                        status = "<span class='label label-info'>空闲</span>";
                    } else if (data.status == 2) {
                        status = "<span class='label label-warning'>忙碌</span>";
                    } else if (data.status == 3) {
                        status = "<span class='label label-danger'>离线</span>";
                    }
                    // console.log(data);
                    var linesStr = '';
                    // debugger
                    if (data.lines != null && data.lines.length != 0) {
                        for (var i = 0; i < data.lines.length; i++) {
                            linesStr += data.lines[i].name;
                            if (i != data.lines.length - 1) {
                                linesStr += ',';
                            }
                        }
                    }
                    console.debug("data.carNumber:" + data.carNumber + "   data.carName:" + data.carName + "   status:" + data.status);
                    newcontent += "<tr class='grid-data tr-hui'  >" +
                        "<td>" + status + "</td>" +
                        "<td>" + data.carNumber + "</td>" +
                        "<td>" + data.carName + "</td>" +
                        (isMainCompany ? ("<td>" + data.companyName + "</td>") : "") +
                        "<td>" + linesStr + "</td>" +
                        "<td>" + (data.employName == null ? "--" : data.employName) + "</td>" +
                        "<td>" + data.ridepeopleNumber + "</td>" +
                        "<td>" + allButton + "</td>" +
                        "</tr>";
                });
            }
            if (!isappend) {
                $("#car_tbody .grid-data").remove();
            }
            $("#car_tbody").append(newcontent);
            $("#car_tbody .grid-data").each(function (index, element) {
                $(element).fadeIn(200 + (index * 35));
            });
            if (!hasShowPages) {
                if (!isappend) {
                    currentTotalElements = result.content[0].cars.length;
                    pageLoading = true;
                } else {
                    if (currentTotalElements < totalElements) {
                        currentTotalElements += result.content[0].cars.length;
                        pageLoading = true;
                    } else {
                        pageLoading = false;
                    }
                }
            }
            if (hasShowPages) {
                firstLoadPages = true;
                $(".pageshow li a").html("共" + totalElements + " 条数据");
                $(".pagedata").paging(totalElements, {
                    format: '[< ncnnn >]',
                    perpage: pagingLimit,
                    page: (offset / limit) + 1,
                    onSelect: function (page) {
                        limit = pagingLimit;
                        offset = (page - 1) * limit;
                        if (!firstLoadPages) {
                            initdata(false);
                        }
                        firstLoadPages = false;
                        return false;
                    },
                    onFormat: function (type) {
                        switch (type) {
                            case 'block': // n and c
                                if (!this.active)
                                    return '';
                                else if (this.value != this.page)
                                    return '<li><a href="#">' + this.value + '</a></li>';
                                return '<li class="active"><a href="#">' + this.value + '</a></li>';
                            case 'next': // >
                                return '<li><a href="#">&rsaquo;</a><li>';
                            case 'prev': // <
                                return '<li><a href="#">&lsaquo;</a><li>';
                            case 'first': // [
                                return '<li><a href="#">&laquo;</a><li>';
                            case 'last': // ]
                                return '<li><a href="#">&raquo;</a></li>';
                        }
                    }
                });
            }
            else {
                //滚动达到pagingLimit条开始显示分页
                if (currentTotalElements == pagingLimit) {
                    pageLoading = false;
                    hasShowPages = true;
                    $(".pageshow").show();
                    $(".pagedata").show();
                    $(".pageshow li a").html("共" + totalElements + " 条数据");
                    $(".pagedata").paging(totalElements, {
                        format: '[< ncnnn >]',
                        perpage: pagingLimit,
                        onSelect: function (page) {
                            limit = pagingLimit;
                            offset = (page - 1) * limit;
                            if (!firstLoadPages) {
                                initdata(false);
                            }
                            firstLoadPages = false;
                            return false;
                        },
                        onFormat: function (type) {
                            switch (type) {
                                case 'block': // n and c
                                    if (!this.active)
                                        return '';
                                    else if (this.value != this.page)
                                        return '<li><a href="#">' + this.value + '</a></li>';
                                    return '<li class="active"><a href="#">' + this.value + '</a></li>';
                                case 'next': // >
                                    return '<li><a href="#">&rsaquo;</a><li>';
                                case 'prev': // <
                                    return '<li><a href="#">&lsaquo;</a><li>';
                                case 'first': // [
                                    return '<li><a href="#">&laquo;</a><li>';
                                case 'last': // ]
                                    return '<li><a href="#">&raquo;</a></li>';
                            }
                        }
                    });
                }
            }
        }
    });
}

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
